<!-- 管理组织 -->
<template>
    <div>
        <div style="display: flex;align-items: center;margin-bottom: 4%;">
            <div>
                组织名称：
            </div>
            <div style="width: 30%;margin-right: 2%;">
                <el-input v-model="companyName" placeholder="请输入组织名称"></el-input>
            </div>
            <el-button type="primary" @click="queryCompanyAndDepartPage({ companyName: companyName })"> 查询</el-button>
            <el-button @click="() => { companyName = ''; queryCompanyAndDepartPage(); }"> 清空</el-button>
        </div>
        <!-- <Table ref="table" :tableData="tableData" :columns="columns" :operationColumn="operationColumn"
            :buttons="buttons" :pagination="pagination" @page-change="handlePageChange" @size-change="handleSizeChange"
            @clickRow="clickRow" /> -->

        <!-- 多级分类表格 -->
        <dragTreeTable :data="treeData" :onDrag="onTreeDataChange" onlySameLevelCanDrag ref='tree'></dragTreeTable>

        <!-- 查看员工 -->
        <el-dialog title="查看员工" :visible.sync="viewTheEmployeesDialogBox" width="80%" @close="closed">
            <template-table ref="template" :url="selUrl" :temTable="temTable"
                @tableBtnClick="tableBtnClick"></template-table>
        </el-dialog>

    </div>
</template>
<script>
import templateTable from "#/views/templates/templateTable";
import dragTreeTable from "drag-tree-table";
import Table from "@/components/Table.vue"; // 引入表格组件
import API from "@/api/api.js";
export default {
    components: {
        Table, // 注册表格组件
        dragTreeTable,
        templateTable,
    },
    data() {
        return {
            selUrl: "/web/org/depart/queryEmployeeByDepartCode.json",
            temTable: {
                // selection: {
                //   state: true,
                //   params: []
                // },
                tableHead: [
                    {
                        prop: "companyName",
                        label: "公司名称",
                    },
                    {
                        prop: "employeeName",
                        label: "员工名称",
                    },
                    {
                        prop: "positionName",
                        label: "公司职位",
                    },
                    {
                        prop: "dataState",
                        label: "状态",
                        template: {
                            "-1": "停用",
                            0: "启用",
                            1: "待审核",
                            3: "审核拒绝",
                        },
                    },
                ],
                tableBtn: [
                    {
                        label: "删除",
                        state: true,
                        id: "delete",
                    },
                ],
            },
            viewTheEmployeesDialogBox: false, //查看员工弹框
            treeData: {
                columns: [
                    {
                        type: "checkbox",
                        title: "选择",
                        field: "",
                        align: "center",
                        onChange: (selectRows) => {
                            // alert('一共选择了' + selectRows.length + '条数据')
                            console.log('选择多行数据列表的：', selectRows)
                            this.$emit('selectRowChange', selectRows)
                        }
                    },
                    {
                        type: "selection",
                        title: "组织名称",
                        field: "companyName",
                        width: 400,
                        align: "center",
                        formatter: (item) => {
                            return "<a>" + item.companyName + "</a>";
                        },
                    },
                    //普通文本显示列
                    {
                        type: "",
                        title: "组织编号",
                        field: "departCode",//文本列字段
                        width: 400,
                        align: "center",
                    },
                    // {
                    //     type: "checkbox",
                    //     isContainChildren: true, //是否勾选子节点，默认false
                    //     onChange: this.onCheck, // parmas selectRows
                    //     title: "链接",
                    //     field: "url",
                    //     width: 200,
                    //     align: "center",
                    // },
                    {
                        title: "操作",
                        type: "action",
                        width: 350,
                        align: "center",
                        actions: [
                            {
                                text: "查看员工",
                                onclick: (item) => {
                                    // item是当前行的数据
                                    this.viewa(item);
                                    console.log('查看员工:', item);
                                    if (Array.isArray(item.departList)) {
                                        this.selUrl = "/web/org/depart/queryEmployeeByDepartCode.json?companyCode=" + item.companyCode
                                    }
                                    if (Array.isArray(item.chileOrgDepartReDomainList)) {
                                        this.selUrl = "/web/org/depart/queryEmployeeByDepartCode.json?departCode=" + item.departCode
                                    }
                                    this.$nextTick(() => {
                                        this.$refs.template.getDataList(this.selUrl);
                                    });
                                    this.viewTheEmployeesDialogBox = true;
                                },
                                formatter: (item) => {
                                    return "<i>查看员工</i>";
                                },
                            },
                            // {
                            //     text: "编辑",
                            //     onclick: (item) => {
                            //         // item是当前行的数据
                            //         console.log(item);
                            //     },
                            //     formatter: (item) => {
                            //         return "<i>编辑</i>";
                            //     },
                            // },
                        ],
                    },
                ],
                lists: [
                    {
                        id: 40,
                        parent_id: 0,
                        order: 0,
                        name: "动物类",
                        uri: "/masd/ds",
                        open: true,
                        lists: [],
                    },
                    {
                        id: 5,
                        parent_id: 0,
                        order: 1,
                        name: "昆虫类",
                        uri: "/masd/ds",
                        open: true,
                        isShowCheckbox: false, //'如果设置了type=checkbox,但是想控制某些行不显示CheckBox，可以用此属性'
                        lists: [
                            {
                                id: 13,
                                parent_id: 5,
                                open: true,
                                order: 0,
                                name: "蚂蚁",
                                uri: "/masd/ds",
                                lists: [],
                            },
                            {
                                id: 12,
                                parent_id: 5,
                                open: true,
                                order: 1,
                                name: "蚂蚁2",
                                uri: "/masd/ds",
                                lists: [],
                            },
                            {
                                id: 11,
                                parent_id: 5,
                                open: true,
                                order: 2,
                                name: "蚂蚁3",
                                uri: "/masd/ds",
                                lists: [],
                            },
                        ],
                    },
                    {
                        id: 19,
                        parent_id: 0,
                        order: 2,
                        name: "植物类",
                        uri: "/masd/ds",
                        open: true,
                        lists: [],
                    },
                ],
            },
            companyName: '',//组织名称
            // 表格行数据列表
            tableData: [
                { companyName: { data: '组织名称1', templateStr: `<div > 你好</div>` }, },
            ],
            //表头
            columns: [
                { label: '组织名称', prop: 'companyName', width: 'auto' }
            ],
            // 操作列按钮：直接传入方法比父子监听更方便
            operationColumn: {
                width: 'auto',
                operationButtons: [
                    { label: '查看员工', type: 'primary', action: this.deleteRow, plain: true, },
                    // { label: '编辑', type: 'primary', action: this.editRow, plain: true, },
                    // { label: '删除', type: 'danger', action: this.deleteRow, plain: true, }
                ],
            },
            // 底部按钮：直接传入方法比父子监听更方便
            buttons: [
                // { label: '切换第二第三行', action: this.toggleSelectionRows },
                // { label: '取消选择', action: this.clearSelection }
            ],
            // 分页
            pagination: {
                currentPage: 1, // 当前页
                pageSize: 5,    // 每页显示的条数（修改为5）
                total: 0        // 总记录数：数据库能拿到的最多记录数
            }
        };
    },
    mounted() {
        this.queryCompanyAndDepartPage()
        //初始化，网络请求第一页数据：请求5条
        // this.tableData = [
        //     { companyName: { data: '组织名称1', templateStr: `<div > 你好1</div>` }, },
        // ]  
        // API.queryCompanyAndDepartPage().then(res => {
        //     console.log('查询组织架构数据', res)

        //     this.treeData.lists = res;
        //     this.treeData.lists.map((item, index) => {
        //         // 有二级
        //         if (Array.isArray(item.departList)) {
        //             item.id = index;
        //             item.parent_id = 0;
        //             item.name = item.companyName;
        //             item.open = true;
        //             // item.order = 0;//排序
        //             item.lists = item.departList.map((item2, index2) => {
        //                 // 处理二级数据并返回
        //                 item2.id = Number(index + index2);
        //                 item2.parent_id = index;
        //                 item2.companyName = item2.departName;
        //                 item2.open = true;
        //                 // item2.order = 0;

        //                 if (Array.isArray(item2.chileOrgDepartReDomainList)) {
        //                     //3级别
        //                     item2.lists = item2.chileOrgDepartReDomainList.map((item3, index3) => {
        //                         // 处理二级数据并返回
        //                         item3.id = Number(index2 + index3);
        //                         item3.parent_id = item2.id;
        //                         item3.companyName = item3.departName;
        //                         item3.open = true;
        //                         // item3.order = 0;
        //                         item3.lists = [];

        //                         if (Array.isArray(item3.chileOrgDepartReDomainList)) {
        //                             //4级别
        //                             item3.lists = item3.chileOrgDepartReDomainList.map((item4, index4) => {
        //                                 // 处理二级数据并返回
        //                                 item4.id = Number(index3 + index4);
        //                                 item4.parent_id = item3.id;
        //                                 item4.companyName = item4.departName;
        //                                 item4.open = true;
        //                                 // item4.order = 0;
        //                                 item4.lists = [];
        //                                 return item4;
        //                             });
        //                         } else {
        //                             item3.lists = [];
        //                         }

        //                         return item3;
        //                     });
        //                 } else {
        //                     item2.lists = [];
        //                 }

        //                 return item2; // 需要返回 item2，确保它被加入到 lists 中
        //             });
        //         } else {
        //             item.id = index;
        //             item.parent_id = 0;
        //             item.name = item.companyName;
        //             item.open = true;
        //             // item.order = 0;
        //             item.lists = []; // 保证结构一致，修改为 `lists`
        //         }
        //     });

        //     // this.tableData = res.map((item, index) => {
        //     //     return {
        //     //         ...item,
        //     //         companyName: {
        //     //             data: item.companyName,
        //     //             templateStr: `<div style="text-align:left;cursor: pointer;">▷ &nbsp;${item.companyName}</div>`,
        //     //             clicked: false,//还没有点击
        //     //             keyName: 'companyName'
        //     //         },
        //     //     }
        //     // })
        //     //更新总条数
        //     this.pagination.total = res.length
        // })
    },
    methods: {
        //查询组织封装
        queryCompanyAndDepartPage(params) {
            API.queryCompanyAndDepartPage(params).then(res => {
                console.log('查询组织架构数据', res)

                this.treeData.lists = res;
                this.treeData.lists.map((item, index) => {
                    // 有二级
                    if (Array.isArray(item.departList)) {
                        item.id = index;
                        item.parent_id = 0;
                        item.name = item.companyName;
                        item.open = true;
                        // item.order = 0;//排序
                        // 第一层就不要显示复选框啦
                        item.isShowCheckbox = false

                        item.lists = item.departList.map((item2, index2) => {
                            // 处理二级数据并返回
                            item2.id = Number(index + index2);
                            item2.parent_id = index;
                            item2.companyName = item2.departName;
                            item2.open = true;
                            // item2.order = 0;
                            // 第2层就不要显示复选框啦
                            item2.isShowCheckbox = false
                            if (Array.isArray(item2.chileOrgDepartReDomainList)) {
                                //3级别
                                item2.lists = item2.chileOrgDepartReDomainList.map((item3, index3) => {
                                    // 处理二级数据并返回
                                    item3.id = Number(index2 + index3);
                                    item3.parent_id = item2.id;
                                    item3.companyName = item3.departName;
                                    item3.open = true;
                                    // item3.order = 0;
                                    item3.lists = [];
                                    // 第3层就不要显示复选框啦
                                    item3.isShowCheckbox = false
                                    if (Array.isArray(item3.chileOrgDepartReDomainList)) {
                                        //4级别
                                        item3.lists = item3.chileOrgDepartReDomainList.map((item4, index4) => {
                                            // 处理二级数据并返回
                                            item4.id = Number(index3 + index4);
                                            item4.parent_id = item3.id;
                                            item4.companyName = item4.departName;
                                            item4.open = true;
                                            // item4.order = 0;
                                            item4.lists = [];
                                            // item4.isShowCheckbox = false
                                            return item4;
                                        });
                                    } else {
                                        item3.lists = [];
                                    }

                                    return item3;
                                });
                            } else {
                                item2.lists = [];
                            }

                            return item2; // 需要返回 item2，确保它被加入到 lists 中
                        });
                    } else {
                        item.id = index;
                        item.parent_id = 0;
                        item.name = item.companyName;
                        item.open = true;
                        // item.order = 0;
                        item.lists = []; // 保证结构一致，修改为 `lists`
                    }
                });

                // this.tableData = res.map((item, index) => {
                //     return {
                //         ...item,
                //         companyName: {
                //             data: item.companyName,
                //             templateStr: `<div style="text-align:left;cursor: pointer;">▷ &nbsp;${item.companyName}</div>`,
                //             clicked: false,//还没有点击
                //             keyName: 'companyName'
                //         },
                //     }
                // })
                //更新总条数
                this.pagination.total = res.length
            })
        },
        editRow(row) {
            console.log('编辑行', row);
        },
        deleteRow(row) {
            console.log('删除行', row);
        },
        //切换选中的行
        toggleSelectionRows() {
            //切换指定的几行的选中状态
            this.$refs.table.toggleSelection([this.tableData[1], this.tableData[2]]);

        },
        //取消所有的选中状态
        clearSelection() {
            this.$refs.table.toggleSelection();//传入行数组是所有的行取消选中状态，传入行数组是取消指定的几行选中状态
        },
        handlePageChange(page) {
            console.log('分页改变:', page);
            // 更新当前页码
            this.pagination.currentPage = page;
            //网络请求指定的页的数据：传入指定的第几页pagination.currentPage和每页要拿多少条数据 pagination.pageSize
            //然后重新赋值给表格数据：根据当前页码来网络请求指定的几条数
            // if (this.pagination.currentPage == 1) {
            //     this.tableData = [
            //         { companyName: '组织名称1', templateStr: `<div> 你好</div>` },]
            // } else if (this.pagination.currentPage == 2) {
            //     this.tableData = [
            //         { companyName: '组织名称2', templateStr: `<div> 你好2</div>` },]
            // } else if (this.pagination.currentPage == 3) {
            //     this.tableData = [
            //         { companyName: '组织名称3', templateStr: `<div> 你好3</div>` },]
            // }
        },
        //用户点击了分页的下拉框：父亲应该修改每次的请求条数了
        handleSizeChange(size) {
            console.log('每页显示条数变化:', size);
            // 更新每页条数
            this.pagination.pageSize = size;
        },
        //点击表格行：
        clickRow(rowIndex, row, keyName, data) {
            console.log(rowIndex, row, keyName, data);
            // this.tableData.map((item, index) => {
            //     if (keyName == 'companyName' && index == rowIndex && !item.companyName.clicked) {
            //         console.log('item:', item);

            //         item.companyName.templateStr = `<div style="text-align:left;cursor: pointer;">▽ &nbsp;${item.companyName.data}</div>`
            //         item.companyName.clicked = true
            //     } else if (keyName == 'companyName' && index == rowIndex && item.companyName.clicked) {
            //         console.log('item:', item);

            //         item.companyName.templateStr = `<div style="text-align:left;cursor: pointer;">▷ &nbsp; ${item.companyName.data}</div>`
            //         item.companyName.clicked = false
            //     }
            // })
        },
        viewa(item) {
            console.log(this.$refs.tree.GetLevelById(item.id), 'this.$refs.tree')
            this.$refs.tree.GetLevelById(item.id);
            this.$refs.tree.GetChildIds(item.id);
        },
        onTreeDataChange(list) {
            console.log(list, "list");

            this.treeData.lists = list;
        },
        closed() {
            this.viewTheEmployeesDialogBox = false;
        },
        tableBtnClick(data, item, index) {
            console.log('item.id', item.id, data);
            if (item.id === "delete") {
                this.$confirm('此操作将永久删除该员工, 是否继续?', '警告：', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(_ => {
                    API.deleteDepartempByPC({ departempId: data.departempId }).then(res => {
                        console.log('res:', res);
                        if (res.success) {
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                        } else {
                            this.$message({
                                type: 'error',
                                message: res.msg
                            });
                        }
                    }).catch(err => {
                        this.$message({
                            type: 'error',
                            message: err.msg
                        });
                    })
                }).catch(_ => {
                });
            }
        }
    }
};
</script>

<style scoped>
/* 父组件的样式 */
</style>
